﻿// <author>Netmon Cipher Dev Team</author>
// <date>2009-07-16</date>
// <version>1.0</version>
// <summary>
// This contains Utility Functions of
// the Common Framework.
// </summary>

namespace DecryptionExpertFramework
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    
    /// <summary>
    /// This contains Utility Functions of
    /// the Common Framework.
    /// </summary>
    public static class DefUtils
    {
        /// <summary>
        /// Reads Properties from Config File.
        /// </summary>
        /// <param name="configFileName">
        /// Name of Config File.
        /// </param>
        /// <returns>
        /// Returns Dictionary of Properties.
        /// </returns>
        public static Dictionary<string, string> GetConfigProperties(
                                            string configFileName)
        {
            string[] properties;
            Dictionary<string, string> configProp = new Dictionary<string, string>();

            XmlDocument doc = new XmlDocument();
            doc.Load(configFileName);
            XmlNodeList nodeList = doc.SelectNodes("/config/Properties/Property");

            foreach (XmlNode node in nodeList)
            {
                string nodeData = node.OuterXml;
                properties = nodeData.Split('\"');
                configProp.Add(properties[1], properties[3]);
            }

            return configProp;
        }

        /// <summary>
        /// Modifies th Config file
        /// </summary>
        /// <param name="configFileName">
        /// Name of config file
        /// </param>
        /// <param name="decryptedCaptureFileName">
        /// Name of decrypted capture file
        /// </param>
        public static void UpdateConfigFile(
                                    string configFileName,
                                    ref string decryptedCaptureFileName)
        {
            string tempFileName = Path.GetTempPath() + "Temp.cap";

            if (File.Exists(tempFileName))
            {
                File.Delete(tempFileName);
            }

            File.Create(tempFileName);

            File.Copy(decryptedCaptureFileName, tempFileName);
            XmlDocument doc = new XmlDocument();
            doc.Load(configFileName);
            XmlNodeList nodeList = doc.SelectNodes("/config/Properties/Property");

            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes[0].Value == "EncryptedCaptureFile")
                {
                    node.Attributes[1].Value = tempFileName;
                    break;
                }
            }

            doc.Save(configFileName);
            nodeList = null;
            doc = null;
        }
    }
}
